//
//  WriteNoteViewController.m
//  PlayView
//
//  Created by houshijia on 16/10/9.
//  Copyright © 2016年 houshijia. All rights reserved.
//

#import "WriteNoteViewController.h"
#import <dangxiao_tool/SCHeader.h>
#import "dangXiaoHeader_note.h"
#import "JSTextView.h"
#import <Masonry/Masonry.h>
@interface WriteNoteViewController ()<UITextViewDelegate>
{
    UIScrollView *_mainScrollView;
    UIView *_topView;
    UIView *_middleView;
    UIButton *_submitButton;//提交按钮
    NSString *_number;
    
    //显示章节信息以及字数统计200字
    UIView *_infoView;
    UIView *_line;
    UILabel *_mlLabel;
    UILabel *_numLabel;
    UIImageView *_iconImg;
}
@property (nonatomic,strong) UIButton *xBtn;
@property (nonatomic,strong) UIButton *sendBtn;
@property (nonatomic, strong) JSTextView *jsTextView;
@property (nonatomic,strong) UIImageView *img;
@end

@implementation WriteNoteViewController
@synthesize img;

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_jsTextView becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    //标题
    [self setNavBarTitle:@"写笔记"];
    //左按钮
    [self.xBtn setImage:[SCToolManager imageWithName:@"导航栏-关闭" InBundle:@"note_image" className:[self class]] forState:UIControlStateNormal];
    [self.navbar setLeftBtn:self.xBtn];
    [self.xBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    
    //右按钮
    [self.sendBtn setTitle:@"发布" forState:UIControlStateNormal];
    self.sendBtn.titleLabel.font = NormalFont(30);
    [self.navbar setRightBtn:self.sendBtn];
    [self.sendBtn addTarget:self action:@selector(sendNote:) forControlEvents:UIControlEventTouchUpInside];
    
    [self createUI];
}

#pragma mark- 布局
-(void)createUI{
    UIScrollView *bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH, SIZEHEIGHT)];
    
    bigScrollView.contentSize = CGSizeMake(0, 568);
    
    
    [self.view addSubview:bigScrollView];
    
    _number = @"1";//默认公开
    
    bigScrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    //顶部大view
    _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SIZEWIDTH, 366/2+90/2+0.5)];
    _topView.backgroundColor = [UIColor whiteColor];
    [bigScrollView addSubview:_topView];
    
    //
    _middleView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_topView.frame)+10, SIZEWIDTH, 108/2)];
    _middleView.backgroundColor = [UIColor whiteColor];
    [bigScrollView addSubview:_middleView];;
    

    
    /*textFeild文字居上*/
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    _jsTextView = [[JSTextView alloc]initWithFrame:CGRectMake(15,15, SIZEWIDTH-30, _topView.frame.size.height-45-20)];
    _jsTextView.delegate = self;
    _jsTextView.backgroundColor = [UIColor redColor];
    
    [_topView addSubview:_jsTextView];

//    //1.设置提醒文字
   
    _jsTextView.myPlaceholder=@"记录一下吧...";

//    //2.设置提醒文字颜色
  
    _jsTextView.myPlaceholderColor= Color_title_black_26;
    
    _jsTextView.backgroundColor = [UIColor whiteColor];
    
    _jsTextView.layer.masksToBounds = YES;
    
    _jsTextView.layer.cornerRadius = 3;
    
    _jsTextView.textColor = Color_title_black_64;
    
    _jsTextView.font = NormalFont(28);
    
    _infoView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.frame.size.height-45, SIZEWIDTH, 45)];
    _infoView.backgroundColor = [UIColor whiteColor];
    
    [_topView addSubview:_infoView];
    
    _line = [[UIView alloc]init];
    _line.backgroundColor = Color_line;
    [_infoView addSubview:_line];
    [_line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(@0.5);
        make.top.mas_equalTo(_infoView.mas_top);
        make.left.equalTo(_infoView.mas_left).offset(0);
        make.right.equalTo(_infoView.mas_right).offset(0);
    }];
    
    _iconImg = [[UIImageView alloc]init];
    _iconImg.image = [SCToolManager imageWithName:@"课程定位" InBundle:@"note_image" className:[self class]];
    [_iconImg setContentMode:UIViewContentModeScaleAspectFit];
    //    _iconImg.backgroundColor = [UIColor redColor];
    [_infoView addSubview:_iconImg];
    [_iconImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_infoView.mas_top).offset(45/2-17/2);
        make.left.equalTo(_infoView).offset(15);
        make.width.mas_equalTo(@(18));
        make.height.mas_equalTo(@(18));
        //        make.bottom.equalTo(_infoView.mas_bottom).offset(-48/3);
        
    }];
    _numLabel = [[UILabel alloc]init];
    _numLabel.backgroundColor = Color_title_black_26;
    _numLabel.layer.masksToBounds = YES;
    _numLabel.layer.cornerRadius = 2;
    _numLabel.backgroundColor = Color_background;
    _numLabel.font = NormalFont(24);
    _numLabel.textAlignment = NSTextAlignmentCenter;
    _numLabel.textColor = Color_title_black_64;
    _numLabel.text = @"200";
    
    [_infoView addSubview:_numLabel];
    [_numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_infoView.mas_top).offset(45/2-23/2);
        make.bottom.equalTo(_infoView.mas_bottom).offset(-(45/2-23/2));
        make.right.equalTo(_line.mas_right).offset(-15);
        make.width.mas_equalTo(76/2);
    }];
    
    _mlLabel = [[UILabel alloc]init];
    _mlLabel.text = _jmc;
    _mlLabel.textColor = Color_title_black_87;
    _mlLabel.font = NormalFont(22);
    [_infoView addSubview:_mlLabel];
    [_mlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_iconImg.mas_right).offset(5);
        make.top.equalTo(_iconImg.mas_top).offset(0);
        make.bottom.equalTo(_iconImg.mas_bottom).offset(0);
        make.right.equalTo(_numLabel.mas_left).offset(-10);
    }];
    
    
    UIView *lastLine0 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_topView.frame), SIZEWIDTH, 0.5)];
    [bigScrollView addSubview:lastLine0];
    lastLine0.backgroundColor = Color_line;
    UIView *lastLine1 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMinY(_middleView.frame)-0.5, SIZEWIDTH  ,0.5)];
    lastLine1.backgroundColor = Color_line;
    [bigScrollView addSubview:lastLine1];
    
    UIView *lastLine2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_middleView.frame), SIZEWIDTH, 0.5)];
    lastLine2.backgroundColor = Color_line;
    [bigScrollView addSubview:lastLine2];
    
    
    UIView *open = [[UIView alloc]initWithFrame:CGRectMake(15, 0, 100, 54)];
    [_middleView addSubview:open];
    img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 54/2-9, 18, 18)];
    img.image =  [SCToolManager imageWithName:@"是否公开-normal" InBundle:@"note_image" className:[self class]]; 
    img.highlightedImage = [SCToolManager imageWithName:@"是否公开-pass" InBundle:@"note_image" className:[self class]];
    img.highlighted = YES;
    [open addSubview:img];
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(18+5, 0, 60, 54)];
    lbl.text = @"笔记公开";
    lbl.font =NormalFont(28);
    lbl.textColor=Color_title_black_87;
    [open addSubview:lbl];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseBtn:)];
    [open addGestureRecognizer:tap];
}

-(void)chooseBtn:(UITapGestureRecognizer*)sender{
    if (_number.integerValue==1) {
        _number = @"0";
        img.highlighted = NO;
    }else{
        _number = @"1";
        img.highlighted = YES;
    }
}


-(void)textViewDidChange:(UITextView *)textView{
    
    NSString *str = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    _numLabel.text = [NSString stringWithFormat:@"%ld",200-str.length];
    
    if (str.length > 200) {
        
        textView.text =  [str substringToIndex:200];
        
        _numLabel.text =@"0";
        
    }
}

#pragma mark- 发布
-(void)sendNote:(UIButton*)sender{
    NSString *str = [_jsTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [_jsTextView resignFirstResponder];

    if (str.length==0 || [str isEqualToString:@""]) {
               ALERT_FAIL(@"输入内容不能为空！");
        return;
    }
    else if (_jsTextView.text.length>200){
              ALERT_FAIL(@"最多输入200字");
    }
    
    else{
        [self sendCourseNote];
    }
}
#pragma mark -- 发送笔记

-(void)sendCourseNote{
    

    [self.bijiInfo setObject:_jsTextView.text forKey:@"bjnr"];

    [self.bijiInfo setObject:_number forKey:@"sfgk"];
    
    
    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_wiritNote params:self.bijiInfo];
    [[SCUDUtil sharedInstance] doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
        HUD_SHOW;
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        HUD_HIDDEN
        [self requestSendCrouseNoteFinished:resp.originalDictionary];
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        HUD_HIDDEN
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];
    
    
    
}
#pragma mark - sendCrouseNote成功
-(void)requestSendCrouseNoteFinished:(NSDictionary*)operation{
    
    
    NSDictionary* cacheDic = [NSDictionary dictionaryWithDictionary:operation];
    
    NSLog(@"creartClasscacheDic == %@  %@", cacheDic,cacheDic[@"statusCode"]);
    
    if ([cacheDic[@"status"]integerValue] == 0) {
        

        _jsTextView.text = @"";
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[JLActionManager sharedInstance]showHUDWithLabelText:@"发布成功" imageView:SucceedImage inView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismiss];
            });
            
        });
        
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [[JLActionManager sharedInstance]showHUDWithLabelText:cacheDic[@"statusCode"] imageView:FailImage inView:self.view];
        });
       
    }
    
}

#pragma mark- dismiss
-(void)dismiss{
    [_jsTextView resignFirstResponder];

    [self dismissViewControllerAnimated:YES completion:^{
        if (self.firstViewController) {
             self.firstViewController();
        }
        
       
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(UIButton *)xBtn{
    if (!_xBtn) {
        _xBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    }
    return _xBtn;
}
-(UIButton *)sendBtn{
    if (!_sendBtn) {
        _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    }
    return _sendBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
